<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>拖拽上传</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }

        .box {
            width: 300px;
            height: 200px;
            font-size: 60px;
            color: rgba(0,0,0,.5);
            text-align: center;
            line-height: 200px;
            border: 1px solid #f00;
        }

        .box img {
            width: 100px;

        }

        button{
            margin-top: 20px;
            margin-left: 100px;
            padding: 12px 40px;
            font-size: 16px;
            letter-spacing: .1rem;
            background-color: #fff;
            border-radius: 3px;
            border: 1px solid #999;
        }
    </style>
</head>
<body>
    <div class="box">
        拖拽到此处
    </div>

    <button>上传</button>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        var fileBody = null;

        // dragstart  dragover  drop
        $(".box").on("dragover", function (){
            // 为了让 drop 事件执行
            event.preventDefault();
        })

        $(".box").on("drop", function (){
            // 阻止浏览器默认读取文件
            event.preventDefault();
            // console.log(event.dataTransfer.files[0]);
            var file = event.dataTransfer.files[0];
            fileBody = file;
            var fileReader = new FileReader();
            fileReader.onload = function (){
                $(".box").html(`<img src="${ this.result }">`);
            }
            fileReader.readAsDataURL(file);
        })

        $("button").click(function (){
            var formData = new FormData();
            formData.append("file", fileBody);

            $.ajax({
                url: "http://www.bufantec.com/api/test/user/upload",
                type: "POST",
                data: formData,
                contentType: false, // 不设置请求头
                processData: false, // jQ 会处理参数，阻止处理
                success(res){
                    console.log(res);
                }
            })
        })
    </script>
</body>
</html>